package com.heroh.util;

import org.hibernate.validator.HibernateValidator;
import org.springframework.util.StringUtils;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.util.Set;

/**
 * 包名称：com.heroh.util
 * 类名称：ValidUtil
 * 类描述：参数校验工具类
 * 创建人：@author jianshengxiong
 * 创建时间：2020/1/9/15:58
 */
public class ValidUtil {

    public static void serviceValid(Object object){
        String validMessage = "";
        //初始化检查器。
        ValidatorFactory validatorFactory = Validation.byProvider( HibernateValidator.class )
                .configure()
                .failFast( false )
                .buildValidatorFactory();
        Validator validator = validatorFactory.getValidator();
        //检查object
        Set<ConstraintViolation<Object>> set = validator.validate(object);
        //循环set，获取检查结果
        for(ConstraintViolation<Object> voset : set){
            validMessage = validMessage + voset.getMessage() +";";
        }
        if(!StringUtils.isEmpty(validMessage)){
            //抛出业务异常
            throw new RuntimeException(validMessage);
        }
    }
}
